const express = require("express"), MBTiles = require('@mapbox/mbtiles');

const app = express()

// 自定义跨域中间件
const allowCors = function (req, res, next) {
  res.header('Access-Control-Allow-Origin', req.headers.origin);
  res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');
  res.header('Access-Control-Allow-Headers', 'Content-Type');
  res.header('Access-Control-Allow-Credentials', 'true');
  next();
};
app.use(allowCors);//使用跨域中间件

const port = 13000;
const mbtilesLocation = 'D:\\tile\\vector\\province.mbtiles';

/* Set return header*/
function getContentType(t) {
  let header = {};
  /* Cache*/
  if (t === "json") {
    header["Content-Type"] = "application/json";
    header["Cache-Control"] = "public, max-age=3600";
  }
  /* request specific headers*/
  if (t === "png") {
    header["Content-Type"] = "image/png";
    header["Cache-Control"] = "public, max-age=604800";
  }
  if (t === "jpg") {
    header["Content-Type"] = "image/jpeg";
    header["Cache-Control"] = "public, max-age=604800";
  }
  if (t === "pbf") {
    header["Content-Type"] = "application/octet-stream";
    header["Content-Encoding"] = "gzip";
    header["Cache-Control"] = "public, max-age=604800";
  }

  return header;
}

new MBTiles(mbtilesLocation, function (err, mbtiles) {
  if (err) throw err;
  app.get('/:z/:x/:y.*', function (req, res) {
    const { params } = req
    const { x, y, z } = params
    const extension = params['0']
    res.set(getContentType(extension))
    mbtiles.getTile(z, x, y, function (err, tile, headers) {
      if (err) {
        res.status(404).send('Tile rendering error: ' + err + '\n')
      } else {
        res.send(tile);
      }
    });
  });
});

// actually create the server
app.listen(port, () => {
  console.log(`server started, visit http://localhost:${[port]}`)
});